package com.ebeitech.doorapp.view.homepage.mvppresenter;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.application.EbeiApplication;
import com.ebeitech.doorapp.constants.CommonConstants;
import com.ebeitech.doorapp.db.CommonDBHelper;
import com.ebeitech.doorapp.domain.User;
import com.ebeitech.doorapp.domain.dao.UserDao;
import com.ebeitech.doorapp.http.EbeiErrorCode;
import com.ebeitech.doorapp.http.HttpListener;
import com.ebeitech.doorapp.http.HttpService;
import com.ebeitech.doorapp.http.model.BaseModel;
import com.ebeitech.doorapp.http.model.LoginModel;
import com.ebeitech.doorapp.http.service.HttpCommonServiceRx;
import com.ebeitech.doorapp.view.homepage.mvpview.LoginContract;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.MD5;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.VersionUtil;
import com.google.gson.Gson;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/10/25.
 */
public class LoginPresenter implements LoginContract.Presenter {

	private LoginContract.View mView;

	public LoginPresenter(LoginContract.View view) {
		this.mView = view;
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case 0: {
					Context context = (Context) msg.obj;
					final String userAccount = SPManager.getInstance(EbeiApplication.getContext()).get(SPConstants.USER_ACCOUNT, "");
					final String userPassword = "";
					if (StringUtil.isStringNullOrEmpty(userAccount)) {
						mView.showLoginFrame();
						return;
					} else {
						mView.showUserAccount(userAccount, userPassword);
						doAutoLogin(context, userAccount);
					}
				}
				break;
				default:
					break;
			}

		}
	};

	@Override
	public void autoLogin(Context context) {
		Message message = new Message();
		message.what = 0;
		message.obj = context;
		mHandler.sendMessageDelayed(message, 500);
	}

	public void doAutoLogin(final Context context, String userAccount) {
		new AsyncTask<String, Void, Void>() {
			User user;

			@Override
			protected Void doInBackground(String... params) {
				String userAccount = params[0];
				CommonDBHelper.changeDBHelper(userAccount);
				user = UserDao.getInstance().getUserByAccount(userAccount);
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				super.onPostExecute(aVoid);
				if (user != null && !StringUtil.isStringNullOrEmpty(user.getUserAccount())) {
					EbeiApplication.setUser(user);
					mView.setIsHomeShowVersionUpdateDialog(true);
					mView.loginSuccess();
				} else {
					mView.showLoginFrame();
				}

			}
		}.execute(userAccount);
	}

	/**
	 * 联网登陆
	 * @param userAccount
	 * @param password
	 */
	@Override
	public void doLogin(final String userAccount, final String password) {
		final Context context = EbeiApplication.getContext();
		SPManager.getInstance(context).put(SPConstants.CLIENT_TOKEN, "");
		HttpCommonServiceRx CommonServiceRx = HttpService.getInstance().getRxGsonRetrofit().create(HttpCommonServiceRx.class);
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", userAccount);
		params.put("password", password);
		params.put("grant_type", "password");
		params.put("scope", "server");
		Call<ResponseBody> call = CommonServiceRx.doLogin(params);
		HttpService.getInstance().executeHttp(context, call, new HttpListener<LoginModel>() {
			@Override
			public void onStart() {
				mView.showProgress(context.getString(R.string.ebei_login_doing));
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				String errorMsg = errorCode.getErrorMsg();
				if (StringUtil.isStringNullOrEmpty(errorMsg)) {
					errorMsg = context.getString(R.string.ebei_login_failure);
				}
				loginFail(errorMsg);
			}

			@Override
			public void onSuccess(LoginModel loginModel) {
				String msg = context.getString(R.string.ebei_login_failure);
				if (loginModel != null) {
					if (!StringUtil.isStringNullOrEmpty(loginModel.getAccess_token())) {
						// 登陆成功，获取个人信息
						SPManager.getInstance(context).put(SPConstants.CLIENT_TOKEN, loginModel.getAccess_token());
						Call<ResponseBody> call2 = CommonServiceRx.getUserInfo();
						HttpService.getInstance().executeHttp(context, call2, new HttpListener<BaseModel>() {
							@Override
							public void onStart() {

							}

							@Override
							public void onError(EbeiErrorCode errorCode) {
								String errorMsg = errorCode.getErrorMsg();
								if (StringUtil.isStringNullOrEmpty(errorMsg)) {
									errorMsg = context.getString(R.string.ebei_login_failure);
								}
								loginFail(errorMsg);
							}

							@Override
							public void onSuccess(BaseModel result) {
								if (result != null && result.getRetData() != null) {
									Object retData = result.getRetData();
									User user = new User();
									user.initWithJson(new Gson().toJson(retData));

									loginSuccess(user);
									mView.showLoginFrame();
									mView.dismissProgress();
									return;
								}

								String msg = context.getString(R.string.ebei_login_failure);
								loginFail(msg);
							}
						}, BaseModel.class, false);
						return;
					}

					if (!StringUtil.isStringNullOrEmpty(loginModel.getError_description())) {
						msg = loginModel.getError_description();
					}
				}


				loginFail(msg);
			}
		}, LoginModel.class, false);
	}

	private void loginFail(String errorMsg) {
		mView.showLoginResult(errorMsg);
		mView.showLoginFrame();
		mView.dismissProgress();
	}

	@Override
	public void loginSuccess(User user) {
		user.setLoginStatus("1");
		EbeiApplication.setUser(user);
		UserDao.getInstance().insertOrUpdate(user);
		mView.loginSuccess();
	}

}
